<template>
  <div>
    <crumbs :BreadCrumb="BreadCrumb"></crumbs>
    <div>
      <div class="disflex">
        <el-form :inline="true" :model="searchForm" class="demo-form-inline">
          <div class="search-box">
            <el-form-item label="体检单号">
              <el-input v-model="searchForm.orderNo" clearable></el-input>
            </el-form-item>
            <el-form-item label="姓名">
              <el-input v-model="searchForm.customerName" clearable></el-input>
            </el-form-item>
            <el-form-item label="证件号" @change="getList">
              <el-input v-model="searchForm.credNum" clearable @keyup.enter.native="getList"></el-input>
            </el-form-item>
            <el-form-item label="单位名称">
              <el-input v-model="searchForm.enterpriseName" clearable></el-input>
            </el-form-item>
            <el-form-item label="二级部门">
              <el-input v-model="searchForm.twoLevelDeptName" clearable></el-input>
            </el-form-item>
            <el-form-item label="合同名称">
              <el-input v-model="searchForm.contractName" clearable></el-input>
            </el-form-item>

            <el-form-item label="入库日期">
              <el-date-picker
                  v-model="orderDateRange"
                  type="daterange"
                  placeholder="选择日期"
                  value-format="yyyy-MM-dd"
              >
              </el-date-picker>
            </el-form-item>
            <el-form-item label="缴费状态">
              <el-select v-model="searchForm.payStatus" clearable>
                <el-option label="未支付" :value="0"></el-option>
                <el-option label="已支付" :value="1"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="预约状态">
              <el-select v-model="searchForm.isAppointment" clearable>
                <el-option label="未预约" :value="0"></el-option>
                <el-option label="已预约" :value="1"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button
                  icon="el-icon-search"
                  type="primary"
                  @click="getList"
              ></el-button>
            </el-form-item>
            <el-form-item class="staff_form_btn">
              <el-button @click="showUserDialog">新建预约</el-button>
            </el-form-item>
          </div>
        </el-form>
      </div>
      <div>
        <div class="options_div">
          <h3 style="text-align: right; font-size: 18px; display: inline">
            待检总人数：{{ count.checkCount }}，
            今日的预约人数：{{ count.todayOrderCount }}，
            明天的日预约人数：{{ count.tomorrowOrderCount }}
          </h3>
          <br/>
        </div>
        <el-table
            ref="multipleTable"
            :data="tableData"
            tooltip-effect="dark"
            style="width: 100%"
            @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column prop="orderNo" label="体检单号" width="140">
          </el-table-column>
          <el-table-column prop="customerName" label="姓名" width="120">
          </el-table-column>
          <el-table-column prop="sex" label="性别" width="120">
            <template slot-scope="scope">{{ scope.row.sex|formatSex }}</template>
          </el-table-column>
          <el-table-column prop="age" label="年龄" show-overflow-tooltip>
          </el-table-column>
          <el-table-column prop="telephone" label="联系方式" width="140">
          </el-table-column>
          <el-table-column prop="enterpriseName" label="单位名称" show-overflow-tooltip>
          </el-table-column>
          <el-table-column prop="examType" label="体检类型" show-overflow-tooltip>
            <template slot-scope="scope">{{ scope.row.examType|formatType }}</template>
          </el-table-column>
          <el-table-column prop="packageCustomname" label="体检套餐" show-overflow-tooltip>
          </el-table-column>
          <el-table-column prop="groupName" label="分组" show-overflow-tooltip>
          </el-table-column>
          <el-table-column
              prop="appointmentDate"
              label="预约日期"
              width="140"
              show-overflow-tooltip
          >
            <template slot-scope="scope">{{ scope.row.appointmentDate|formatDate }}</template>
          </el-table-column>
          <el-table-column
              prop="createTime"
              label="入库时间"
              width="140"
              show-overflow-tooltip
          >
            <template slot-scope="scope">{{ scope.row.createTime|formatDate }}</template>
          </el-table-column>
          <el-table-column
              prop="payStatus"
              label="缴费状态"
              show-overflow-tooltip
          >
            <template slot-scope="scope">{{ scope.row.payStatus|formatPayStatus }}</template>
          </el-table-column>
          <el-table-column
              prop="isAppointment"
              label="预约状态"
              show-overflow-tooltip
          >
            <template slot-scope="scope">
              {{ scope.row.isAppointment|formatSubscribe }}
            </template>
          </el-table-column>
          <el-table-column label="操作" fixed="right" width="360">
            <template slot-scope="scope">
              <el-button
                  type="primary"
                  size="mini"
                  @click="changeCheckup(scope.row)"
                  :disabled="scope.row.status===8 || scope.row.isAppointment===1"
              >预约
              </el-button>
              <el-button
                  type="success"
                  size="mini"
                  :disabled="scope.row.status===8"
                  @click="toEditItems(scope.row)"
              >增改项
              </el-button>
              <el-button
                  type="warning"
                  size="mini"
                  :disabled="scope.row.status===8"
                  @click="toRemoveItems(scope.row)"
              >退项
              </el-button>
              <el-button
                  type="primary"
                  size="mini"
                  :disabled="scope.row.status===8"
                  @click="toShowItems(scope.row)"
              >查项
              </el-button>
              <el-button
                  type="danger"
                  size="mini"
                  :disabled="scope.row.status===8 || scope.row.customerType===2 || scope.row.payStatus===1"
                  @click="toRemoveItems(scope.row)"
              >删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="pagination">
        <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="pageNo"
            :page-sizes="[10, 100, 200, 300, 400]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
        >
        </el-pagination>
      </div>
    </div>

    <!-- 体检预约新增、编辑 -->
    <el-dialog
        title="新建预约"
        :visible.sync="userDialog"
        width="70%"
        class="top_dialog"
    >
      <el-form :model="form" label-position="left">
        <div class="add_info">
          <userinfos ref="riskForm" :queryform="queryform" :dictdata="dict"></userinfos>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="addinsertCustom">下一步</el-button>
        <el-button @click="clear">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 编辑个人体检：编辑体检项目 || 增改项-->
    <el-dialog
        title="选择体检项目"
        width="90%"
        height="100%"
        :visible.sync="itemDialog"
        class="top_dialog"
    >
      <!-- 穿梭框-->
      <div style="height: 700px">
        <el-row :gutter="20" class="bg-grey">
          <el-col :span="11">
            <div class="tableTitle">
              <el-form
                  :inline="true"
                  :model="examItemSearchForm"
                  class="demo-form-inline"
              >
                <el-form-item>
                  <el-input
                      v-model="examItemSearchForm.itemName"
                      placeholder="项目名称"
                  ></el-input>
                </el-form-item>
                <el-form-item>
                  <el-button @click="getexamItemList">查找</el-button>
                </el-form-item>
              </el-form>
            </div>
            <!-- :key="tableKey" -->
            <div class="bg-blue">
              <el-table
                  ref="staffTable"
                  :data="examItemList"
                  height="600"
                  border
                  fit
                  highlight-current-row
                  :row-key="record=>record.itemId"
                  @selection-change="handleStaffChange"
              >
                <el-table-column
                    type="selection"
                    :reserve-selection="true"
                    width="55"
                    align="center"
                ></el-table-column>
                <el-table-column label="科室名称" align="center" prop="deptName"></el-table-column>
                <el-table-column label="项目名称" align="center" prop="itemName"></el-table-column>
                <el-table-column label="价格" align="center" prop="price"></el-table-column>

                <el-table-column label="适用范围" align="center" prop="applyTo">
                  <template slot-scope="scope">{{ scope.row.applyTo|formatApplyTo }}</template>
                </el-table-column>
              </el-table>
            </div>
            <div style="margin-top: 20px">
            </div>
          </el-col>
          <el-col :span="2" align="center" class="buttonAll">
            <el-button
                @click="addStaff('single')"
                :disabled="!staffData.length"
                class="staffButton"
                style="margin-top: 150px"
            >
              <i class="el-icon-arrow-right"></i>
              <i class="el-icon-arrow-right"></i>
            </el-button>
            <br/>
            <el-button
                @click="removeStaff('single')"
                :disabled="!selectedStaffData.length"
                class="staffButton"
            >
              <i class="el-icon-arrow-left"></i>
              <i class="el-icon-arrow-left"></i>
            </el-button>
          </el-col>
          <el-col :span="11">
            <div class="tableTitle pb-20">
              当前体检项目列表（{{ selectedItemList.length }}）
              <!-- <span>已选列表</span>
              <span>{{ selectedStaffCheckNum }}/{{ selectedStaffNum }}</span> -->

              <div class="nsm-right-top">
                <el-button type="primary" @click="getPackagesList">选择体检套餐
                </el-button
                >
              </div>
            </div>
            <div class="bg-blue" style="margin-bottom: 15px">
              <el-table
                  ref="selectedStaffTable"
                  :data="selectedItemList"
                  :row-key="record=>record.itemId"
                  height="600"
                  border
                  fit
                  highlight-current-row
                  @selection-change="handleSelectedStaffChange"
              >
                <el-table-column
                    type="selection"
                    :reserve-selection="true"
                    width="55"
                    align="center"
                ></el-table-column>
                <el-table-column label="项目名称" prop="itemName"></el-table-column>
                <el-table-column label="价格" align="center" prop="price"></el-table-column>
                <el-table-column label="适用范围" align="center" prop="applyTo">
                  <template slot-scope="scope">{{ scope.row.applyTo|formatApplyTo }}</template>
                </el-table-column>
              </el-table>
            </div>
            <el-form :inline="true" :model="orderForm" class="demo-form-inline">
              <el-form-item label="待缴费金额">
                <el-input
                    v-model="orderForm.salePrice"
                    clearable
                    style="width: 100px"
                ></el-input>
              </el-form-item>
              <el-form-item label="缴费方式">
                <el-select
                    v-model="orderForm.payment"
                    placeholder="个人"
                    style="width: 120px"
                >
                  <el-option label="个人" :value="0"></el-option>
                  <el-option label="单位" :value="1"></el-option>
                </el-select>
              </el-form-item>
              <el-checkbox v-model="orderIsPay" class="vmm">已缴费</el-checkbox>
            </el-form>
            <div class="nsm-bottom-line" v-if="newCustomer">
              <span>姓名：{{ newCustomer.customerName }}</span>
              <span>性别：{{ newCustomer.sex|formatSex }}</span>
              <span>年龄：{{ newCustomer.age }}</span>
              <span>单位：{{ newCustomer.company }}</span>
            </div>
          </el-col>
        </el-row>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button
            type="success"
            @click="editPeOrdersMain()"
        >保存
        </el-button>
        <el-button @click="itemDialog = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 编辑个人体检：选择体检套餐 -->
    <el-dialog
        title="选择套餐"
        :visible.sync="packageVisible"
        width="90%"
        class="top_dialog"
        append-to-body
    >
      <div style="height: 650px">
        <el-form :inline="true" :model="packageSearchForm" class="demo-form-inline">
          <el-form-item label="">
            <el-input
                v-model="packageSearchForm.queryConditionField"
                placeholder="输入查询关键词"
            ></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="readPackageList">查询</el-button>
          </el-form-item>
        </el-form>
        <el-table
            ref="multipleTable"
            :data="packageList"
            tooltip-effect="dark"
            border
            style="width: 100%"
            :row-key="record=>record.id"
            @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="40"></el-table-column>
          <el-table-column prop="packageCode" label="套餐编号"></el-table-column>
          <el-table-column prop="packageName" label="套餐名称"></el-table-column>
          <el-table-column prop="code" label="代码" show-overflow-tooltip>
          </el-table-column>
          <el-table-column prop="packageType" label="体检类型">
            <template slot-scope="scope">{{ scope.row.examType|formatType }}</template>
          </el-table-column>
          <el-table-column
              prop="applyTo"
              label="适用范围"
              width="80"
              show-overflow-tooltip
          >
            <template slot-scope="scope">{{ scope.row.applyTo|formatApplyTo }}</template>
          </el-table-column>
          <el-table-column
              prop="price"
              label="价格"
              width="80"
              show-overflow-tooltip
          >
          </el-table-column>
          <el-table-column
              prop="unitName"
              label="单位名称"
              show-overflow-tooltip
          >
          </el-table-column>
        </el-table>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="pushItemList">确定</el-button>
        <el-button @click="packageVisible = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 退项-->
    <el-dialog
        title="请选择要退的体检项目"
        width="60%"
        :visible.sync="itemRemoveDialog"
    >
      <div>
        <el-row :gutter="20" class="bg-grey">
          <el-col>
            <div class="tableTitle">
              <el-form
                  :inline="true"
                  :model="examItemSearchForm"
                  class="demo-form-inline"
              >
                <el-form-item>
                  <el-input
                      v-model="examItemSearchForm.itemName"
                      placeholder="项目名称"
                  ></el-input>
                </el-form-item>
                <el-form-item>
                  <el-button @click="getexamItemList">查找</el-button>
                </el-form-item>
              </el-form>
            </div>
            <div class="tableTitle pb-20">
              当前体检项目:{{ selectedItemList.length }}项，合计金额：{{ orderForm.salePrice }}元
            </div>
            <div class="bg-blue" style="height: 270px">
              <el-table
                  ref="selectedStaffTable"
                  :data="selectedItemList"
                  :row-key="record=>record.itemId"
                  max-height="315"
                  border
                  fit
                  highlight-current-row
                  @selection-change="handleSelectedStaffChange"
              >
                <el-table-column
                    type="selection"
                    :reserve-selection="true"
                    width="55"
                    align="center"
                ></el-table-column>
                <el-table-column label="项目名称" prop="itemName"></el-table-column>
                <el-table-column label="价格" align="center" prop="price"></el-table-column>
                <el-table-column label="适用范围" align="center" prop="applyTo">
                  <template slot-scope="scope">{{ scope.row.applyTo|formatApplyTo }}</template>
                </el-table-column>

              </el-table>
            </div>

            <div class="nsm-bottom-line" v-if="newCustomer">
              <span>姓名：{{ newCustomer.customerName }}</span>
              <span>性别：{{ newCustomer.sex|formatSex }}</span>
              <span>年龄：{{ newCustomer.age }}</span>
              <span>单位：{{ newCustomer.company }}</span>
            </div>
          </el-col>
        </el-row>

        <el-row style="margin-top: 50px" type="flex" align="middle">
          <el-col :span="12" class="text-red">
          </el-col>
          <el-col :span="11" :offset="1">
            <el-row>
              <el-button
                  type="success"
                  @click="doRemoveItems()"
              >保存
              </el-button>
              <el-button @click="itemRemoveDialog = false">取 消</el-button>
            </el-row>
          </el-col>
        </el-row>
      </div>
    </el-dialog>

    <!-- 查项-->
    <el-dialog
        title="体检单项目浏览"
        width="60%"
        :visible.sync="itemShowDialog"
        class="top_dialog"
    >
      <div>
        <el-row :gutter="20" class="bg-grey">
          <el-col>
            <div class="tableTitle pb-20">
              当前体检项目:{{ selectedItemList.length }}项，合计金额：{{ orderForm.salePrice }}元
            </div>
            <div class="bg-blue" style="height: 270px">
              <el-table
                  :data="selectedItemList"
                  :row-key="record=>record.itemId"
                  max-height="315"
                  border
                  fit
                  highlight-current-row
              >
                <el-table-column label="项目名称" prop="itemName"></el-table-column>
                <el-table-column label="价格" align="center" prop="price"></el-table-column>
                <el-table-column label="适用范围" align="center" prop="applyTo">
                  <template slot-scope="scope">{{ scope.row.applyTo|formatApplyTo }}</template>
                </el-table-column>
              </el-table>
            </div>

            <div class="nsm-bottom-line" v-if="newCustomer">
              <span>姓名：{{ newCustomer.customerName }}</span>
              <span>性别：{{ newCustomer.sex|formatSex }}</span>
              <span>年龄：{{ newCustomer.age }}</span>
              <span>单位：{{ newCustomer.company }}</span>
            </div>
          </el-col>
        </el-row>

        <el-row style="margin-top: 50px" type="flex" align="middle">
          <el-col :span="12" class="text-red">
          </el-col>
          <el-col :span="11" :offset="1">
            <el-row>
              <el-button @click="itemShowDialog = false">关 闭</el-button>
            </el-row>
          </el-col>
        </el-row>
      </div>
    </el-dialog>

    <!-- 预约 -->
    <el-dialog
        title="预约详情"
        :visible.sync="checkupStatus"
        width="600"
    >
      <el-form :model="checkupForm" label-position="left">
        <el-form-item label="预约时间">
          <el-date-picker v-model="checkupForm.appointmentDate" type="datetime" placeholder="选择日期时间"></el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="createCheckup">保 存</el-button>
        <el-button @click="checkupStatus = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import crumbs from "../../views/Crumbs.vue";
import userinfos from "../common/userinfos.vue";
import {formatTimeToStr} from "@src/common/utils/date";
import {optionsSex} from "@src/common/utils/constant";
import axios from "axios";

export default {
  name: "subscribe",
  components: {
    crumbs,
    userinfos
  },
  data() {
    return {
      BreadCrumb: [
        {path: "", name: "检前管理"},
        {path: "/front/subscribe", name: "预约管理"},
      ],
      examItemSearchForm: {
        pageNo: 1,
        pageSize: 1000
      },
      timehttp:'',
      optionsSex: optionsSex,
      examItemList: [],
      staffData: [],
      staffList: [],
      // 总数
      staffNum: 0,
      // 选中数量
      staffCheckNum: 0,
      // 已选选中
      selectedStaffData: [],
      selectedStaffList: [],
      // 已选总数
      selectedStaffNum: 0,
      // 已选选中数量
      selectedStaffCheckNum: 0,
      // 已选列表
      selectedItemList: [],
      selectedItemIds: [],
      packageSearchForm: {},
      packageList: [],
      orderForm: {
        salePrice:0,
        payStatus: false
      },
      newCustomer: null,
      count: {},
      tableData: [],
      userDialog: false,
      form: {},
      searchForm: {},
      orderDateRange: [
        formatTimeToStr(new Date(new Date().setMonth(new Date().getMonth() - 3)), "yyyy-MM-dd"),
        formatTimeToStr(new Date(), "yyyy-MM-dd")
      ],
      pageSize: 10,
      pageNo: 1,
      total: 0,
      dict: {},
      queryform: {},
      checkForm: {},
      checkupForm: {
        orderId: 0,
        appointmentDate: '',
        appointmentNote: ''
      },
      checkupStatus: false,
      orderIsPay: false,
      packageVisible: false,
      itemDialog: false,
      itemRemoveDialog: false,
      itemShowDialog: false,
    }
  },
  filters: {
    formatSex: function (val) {
      var dict = {1: "男", 2: "女"}
      return dict[val]
    },
    formatSubscribe: function (val) {
      var dict = {1: "已预约", 0: "未预约"}
      return dict[val]
    },
    formatType: function (val) {
      var dict = {1: "普通体检", 2: "单位体检", 3: "入职体检", 4: "职业体检", 5: "婚育体检", 6: "老年专项体检", 7: "健康体检等"}
      return dict[val]
    },
    formatStatus: function (val) {
      var dict = {1: "未登记", 2: "登记", 4: "检中", 8: "交表", 16: "初检", 32: "复检", 64: "打印"}
      return dict[val]
    },
    formatDate: function (time) {
      if (time != null && time !== "") {
        var date = new Date(time);
        return formatTimeToStr(date, "yyyy-MM-dd hh:mm");
      } else {
        return "";
      }
    },
    formatApplyTo: function (val) {
      const dict = {}
      optionsSex.forEach(v => {
        dict[v.value] = v.label
      })
      return dict[val] || val
    },
    formatPayStatus: function (val) {
      var dict = {1: "已缴费", 0: "未缴费"}
      return dict[val]
    }
  },
  beforeDestroy() {
    clearInterval(this.timehttp)
  },
  methods: {
    getList() {
      if (this.orderDateRange && this.orderDateRange.length === 2) {
        this.searchForm.startCreateTime = this.orderDateRange[0]
        this.searchForm.endCreateTime = this.orderDateRange[1]
      } else {
        delete this.searchForm.endCreateTime
        delete this.searchForm.startCreateTime
      }
      this.getCount(this.searchForm)
      this.doGetList(this.searchForm)
    },
    handleSizeChange(val) {
      this.pageSize = val
      const req = {
        ...this.searchForm,
        pageSize: this.pageSize,
        pageNo: this.pageNo,
      }
      this.doGetList(req)
    },
    handleCurrentChange(val) {
      this.pageNo = val
      const req = {
        ...this.searchForm,
        pageSize: this.pageSize,
        pageNo: this.pageNo,
      }
      this.doGetList(req)
    },
    getCount(req) {
      this.$axios.getCheckupNums(req).then(res => {
        this.count = res.data
      })
    },
    doGetList(req) {
      this.$axios.getCheckupList(req).then(res => {
        this.total = res.data.total
        this.tableData = res.data.records
      })
    },
    // 获取字典值
    searchDictList() {
      this.$axios.searchDictList({
        codes: ["tyType", "xmType", "jgType", "mzType", "gwType", "zwType", "ybType", "dwxzType", 'zylbType','zjType'],
      }).then((res) => {
        if (res.code === "00000") {
          res.data.forEach(v => {
            this.dict[v.dictCode] = v.items
          })
        }
      });
    },
    // 新建预约
    showUserDialog() {
      this.userDialog = true
      this.rest()
      this.identityCard()
    },
    clear() {
      this.userDialog = false
      clearInterval(this.timehttp)
    },
    identityCard() {
      this.timehttp = setInterval(() => {
        this.doIdentityCard()
      },2500)
    },
    doIdentityCard(){
      const that = this
      $.ajax({
				type: 'GET',
				timeout: 10000,
				url: 'http://localhost:30088/ID=sfz',
				dataType: 'jsonp',
				success: function(data) {
          if (!data.error) {
            clearInterval(that.timehttp)
            that.timehttp = null
            let stringtext = data.info
            let listarr = stringtext.split("-")
            listarr[0] = listarr[0].trim()
            listarr[5] = listarr[5].trim()
            listarr[6] = listarr[6].trim()
            // 名字
            that.$set(that.queryform, "customerName", listarr[0])
            // 身份证号
            that.$set(that.queryform, "credNum", listarr[4])
            that.$set(that.searchForm, "credNum", listarr[4])
            // 性别
            that.$set(that.queryform, "sex", listarr[1] == "男" ? 1 : 2)
            // 出生日期
            let birthday = listarr[4].slice(6, 14)
            birthday = birthday.replace(/(.{4})(.{2})/, "$1-$2-");
            that.$set(that.queryform, "birth", birthday)
            // 年龄
            var birthDate = new Date(birthday);
            var nowDateTime = new Date();
            var age = nowDateTime.getFullYear() - birthDate.getFullYear();
            that.$set(that.queryform, "age", age)
            // 提交
            const imgfile = that.convertBase64UrlToImgFile(data.base64, listarr[4] + '.jpg', 'image/jpg');
            console.log('imgfile', imgfile)
            that.uploadImg(imgfile, listarr[4])
          }
				},
				error: function(err) {
          console.log('err', err)
				}
			})
    },
    // base64转file
    convertBase64UrlToImgFile(urlData, fileName, fileType) {
      var bytes = window.atob(urlData);
      var ab = new ArrayBuffer(bytes.length);
      var ia = new Int8Array(ab);
      var i;
      for (i = 0; i < bytes.length; i++) {
        ia[i] = bytes.charCodeAt(i);
      }
      var blob = new Blob([ab], {type: fileType});
      blob.lastModifiedDate = new Date();
      blob.name = fileName;
      console.log('file文件', blob)
      return blob;
    },
    // 上传图片
    uploadImg(fileData, name) {
      let formData = new FormData();
      let fileOfBlob = new File([fileData], name + ".jpg");
      formData.append("file", fileOfBlob);
      this.$axios.importFile(formData).then((res)=>{
        if (res.success) {
          this.$set(this.queryform, "photo", res.data)
        }
      })
    },
    rest(){
      this.orderId = null
      this.queryform ={}
      this.orderForm ={}
      this.orderIsPay = false
      this.selectedItemList = []
    },
    // 个人信息编辑
    addinsertCustom() {
      this.$refs.riskForm.$refs.riskFormRef.validate((valid) => {
        if (valid) {
          // 获取子组件form
          this.checkform = this.$refs.riskForm.$refs.riskFormRef.model;
          if(this.checkform.id){
            this.$axios.updatePeCustomers({...this.checkform}).then((res) => {
              if (res.code === "00000") {
                this.newCustomer = this.checkform
                this.checkform = {}
                this.showItemDialog()
                this.userDialog = false
              }
            });
          }else {
            this.$axios.insertPeCustomers({...this.checkform,}).then((res) => {
              if (res.code === "00000") {
                this.newCustomer = res.data
                this.checkform = {}
                this.showItemDialog()
                this.userDialog = false
              }
            });
          }
        }
      });
    },
    reset() {
      this.selectedItemIds = []
      this.selectedItemList = []
      this.examItemList = []
      this.packageList = []
      this.orderId = null
    },

    // 体检项
    showItemDialog() {
      this.itemDialog = true
      this.getexamItemList()
    },
    getexamItemList() {
      this.examItemList = []
      this.$axios.examItemList(this.examItemSearchForm).then(res => {
        if (res.code === '00000') {
          var records = res.data.records
          records.map(item => {
            this.examItemList.push({
              itemId: item.id,
              itemName: item.itemName,
              deptName: item.deptName,
              price: item.price,
              applyTo: item.applyTo
            })
          })
        }
      })
    },

    //退项
    toRemoveItems(row) {
      this.itemRemoveDialog = true
      this.orderForm = {}
      this.orderId = row.id
      this.$axios.getPeOrdersMainById({peOrdersMainId: row.id}).then(res => {
        if (res.code === '00000') {
          const data = res.data;
          this.orderCurr = data
          this.newCustomer = data.peCustomers
          let totalPrice = 0
          data.peOrdersDetails.forEach(item => {
            if (item.isPayed === 1 && item.postType==='个人') {
              totalPrice += item.price
              this.selectedItemList.push({...item, payStatus: data.payStatus})
            }
          })
          this.orderForm.salePrice = parseFloat(totalPrice).toFixed(2)
        }
      })
    },

    doRemoveItems() {
      this.$confirm("此操作将删除该数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        const req = {orderId:this.orderCurr.id}
        this.$axios.deletePeOrdersMain(req).then(res => {
          if (res.code === '00000') {
            this.$message.success("提交成功")
            this.itemRemoveDialog = false
            this.getList()
          }
        })
      });
    },


    //查项
    toShowItems(row) {
      this.selectedItemList = []
      this.itemShowDialog = true
      this.orderForm = {}
      this.orderId = row.id
      this.$axios.getPeOrdersMainById({peOrdersMainId: row.id}).then(res => {
        if (res.code === '00000') {
          const data = res.data;
          this.orderCurr = data
          let totalPrice = 0
          data.peOrdersDetails.forEach(item => {
            if (item.isPayed === 1) {
              totalPrice += item.price
              this.selectedItemList.push({...item, payStatus: data.payStatus})
            }
          })
          this.orderForm.salePrice = parseFloat(totalPrice, 2)
          this.newCustomer = data.peCustomers
        }
      })
    },

    // 新建 增项开单
    // 获取体检登记信息
    toEditItems(row) {
      this.orderForm = {}
      this.orderId = row.id
      this.$axios.getPeOrdersMainById({peOrdersMainId: row.id}).then(res => {
        if (res.code === '00000') {
          this.selectedItemList=[]
          const data = res.data;
          this.orderCurr = data
          this.orderForm.salePrice = data.salePrice
          this.orderIsPay = data.payStatus === 1;
          data.peOrdersDetails.forEach(item => {
            if (item.isPayed !== 1) {
              this.selectedItemList.push({...item, payStatus: data.payStatus})
            }
          })
          this.selectedItemIds = data.peOrdersDetails.map(item => item.itemId)
          this.itemDialog = true
          this.newCustomer = data.peCustomers
        }
      })
      this.getexamItemList()
    },
    editPeOrdersMain() {
      if (this.orderId == null) {
        const req = {
          peOrdersDetails: [],
          salePrice: this.orderForm.salePrice
        }
        this.selectedItemList.map((item, index) => {
          req.peOrdersDetails.push({
            itemId: item.itemId,
            itemName: item.itemName,
            price: item.price
          })
        })
        this.$axios.insertPeOrdersMain({
          ...req,
          customerId: this.newCustomer.id,
          isAppointment: 1,
        }).then(res => {
          if (res.code === '00000') {
            this.$message({
              type: "success",
              message: res.msg,
            });
            this.getList()
            this.itemDialog = false
          }
        })
      } else {
        this.orderCurr.salePrice = this.orderForm.salePrice
        this.orderCurr.payStatus = this.orderIsPay === true ? 1 : 0
        this.orderCurr.peOrdersDetails = this.selectedItemList
        console.log(this.orderCurr.payStatus)
        this.$axios.updatePeOrdersMain(this.orderCurr).then(res => {
          if (res.code === '00000') {
            this.$message({
              type: "success",
              message: res.msg,
            });
            this.getList()
            this.selectedItemIds = []
            this.selectedItemList = []
            this.examItemList = []
            this.packageList = []
            this.itemDialog = false
          }
        })
      }
    },
    // 选择套餐
    getPackagesList() {
      this.packageVisible = true;
      this.$axios.queryPbPackagesList({}).then(res => {
        if (res.code === '00000') {
          this.packageList = res.data.records
        }
      })
    },
    readPackageList() {
      this.$axios.readPackageList(this.packageSearchForm).then(res => {
        if (res.code === '00000') {
          this.packageList = res.data.records
        }
        // console.log(res.data,this.queryform)
      })
    },
    pushItemList() {
      var ids = []
      this.multipleSelection.map(item => {
        ids.push(item.id)
      })

      this.$axios.queryPackagItemsByPackIds({ids: ids}).then(res => {
        if (res.code === '00000') {
          var list = res.data
          list.map(l => {
            l.examItemsDTOList.map(item => {
              if (this.selectedItemIds.indexOf(item.id) < 0) {
                this.selectedItemIds.push(item.id)
                this.selectedItemList.push({
                  itemId: item.id,
                  deptName: item.deptName,
                  itemName: item.itemName,
                  price: item.price
                })
              }
            })
          })
          this.setPrice()
          this.packageVisible = false
        }
      })
    },

    // 穿梭框
    // 左边表格选中存入staffData
    handleStaffChange(rows) {
      this.staffCheckNum = rows.length;
      this.staffData = [];
      if (rows) {
        rows.forEach((row) => {
          if (row) {
            this.staffData.push(row);
          }
        });
      }
    },
    // 左->右(单选-全选)
    addStaff(type) {
      setTimeout(() => {
        // 清空选择
        this.$refs["staffTable"].clearSelection();
        this.$refs["selectedStaffTable"].clearSelection();
      }, 0);
      if (type === "single") {
        console.log(this.staffData)
        this.staffData.forEach((item) => {
          console.log()
          if (this.selectedItemIds.indexOf(item.itemId) >= 0) {
            return
          }
          this.selectedItemIds.push(item.itemId)
          this.selectedItemList.push(item);
          // this.examItemList.forEach((v, i)=>{
          //   if(v.itemId === item.itemId){
          //     this.examItemList.splice(i, 1);
          //   }
          // })
        });
      }
      if (type === "all") {
        this.staffList.forEach((item) => {
          if (this.selectedItemIds.indexOf(item.id) === -1) {
            this.selectedItemList.push(item);
            this.selectedItemIds.push(item.id)
          }
        });
        this.staffList = [];
        this.staffNum = this.staffList.length;
        this.selectedStaffNum = this.selectedItemList.length;
      }
      this.setPrice()
    },
    // 右->左(单选-全选)
    removeStaff(type) {
      setTimeout(() => {
        this.$refs["staffTable"].clearSelection();
        this.$refs["selectedStaffTable"].clearSelection();
      }, 0);
      if (type === "single") {
        // const repeatArr = [];
        // this.selectedStaffData.forEach((item) => {
        //   this.examItemList.forEach((v)=>{
        //     if(v.itemId === item.itemId){
        //       repeatArr.push(item)
        //     }
        //   })
        // })
        // if(repeatArr.length==0){
        //   this.examItemList.push(item);
        // }
        // console.log("右->左")
        this.selectedStaffData.forEach((item) => {
          this.selectedItemList.forEach((v, i) => {
            if (item.itemId === v.itemId) {
              this.selectedItemIds.splice(i, 1);
              this.selectedItemList.splice(i, 1);
            }
          })
        });
      }
      if (type === "all") {
        this.selectedItemList.forEach((item) => {
          this.staffList.push(item);
          this.staffNum = this.staffList.length;
        });

        this.selectedItemList = [];
        this.selectedItemIds = [];
        this.selectedStaffNum = 0;
      }
      // 计算价格
      this.setPrice()
    },
    // 右边表格选中存入selectedStaffData
    handleSelectedStaffChange(rows) {
      this.selectedStaffCheckNum = rows.length;
      this.selectedStaffData = [];
      if (rows) {
        rows.forEach((row) => {
          if (row) {
            this.selectedStaffData.push(row);
          }
        });
      }
    },
    setPrice() {
      var price = 0
      this.selectedItemList.map(item => {
        if (item.price) {
          price = price + parseFloat(item.price)
        }
      })
      this.orderForm.salePrice = price
    },

    // 预约弹框
    handleClick() {
      this.userDialog = true;
    },

    changeCheckup(data) {
      this.checkupForm = data
      this.checkupStatus = true
    },

    createCheckup() {
      const params = {
        ...this.checkupForm,
        appointmentDate:formatTimeToStr(this.checkupForm.appointmentDate)
      }
      this.$axios.setCheckupForm(params).then(res => {
        if (res.code === '00000') {
          this.$message.success('预约成功')
          this.checkupStatus = false
          this.getList()
        }
      })
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
  },
  created() {
    this.getList()
    this.searchDictList()
  }

}
</script>

<style scoped>
.nsm-bottom-line span {
  font-size: 16px;
  font-weight: bold;
  margin-right: 25px;
}

</style>
